import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:tracker/api/index.dart';
import 'package:tracker/common/extension/date_extension.dart';
import 'package:tracker/pages/home/location/model/monitor_data_resp.dart';
import 'package:tracker/pages/home/track/model/track_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/utils/toast_utils.dart';

mixin TrackPageMixin<T extends ConsumerStatefulWidget> on ConsumerState<T> {
  /// 轨迹日历
  List<DateTime> trackCalendar = [];

  /// 日历日期值
  List<DateTime?> calendarValue = const [];

  /// 查询时间
  List<DateTime?> startTimeValue = const [];
  List<DateTime?> endTimeValue = const [];

  /// 是否刷新过轨迹日历数据
  bool isRefreshTrackCalendar = false;

  /// 用户轨迹存储最小日期
  DateTime userMinDate = DateTime.now();

  /// 轨迹存储天数
  int trackStorageDays = 180;

  /// 获取设备实时信息
  Future<MonitorDataResp> getDeviceMonitor(String imei) async {
    return TrackApi.getDeviceMonitor(imei);
  }

  /// 逆地址解析
  Future<String> reverseGeoCode(TrackData trackData) async {
    return TrackApi.reverseGeoCode(trackData.latitude, trackData.longitude, trackData.gpsDataId);
  }

  /// 格式化停留时长时间，格式成时分
  String formatStayTime(num sec) {
    var hour = sec ~/ 3600;
    var minute = sec % 3600 ~/ 60;
    var second = sec % 60;
    // 大于0才拼接
    var hourStr = hour > 0 ? '${hour}小时' : '';
    var minuteStr = minute > 0 ? '${minute}分钟' : '';
    return '$hourStr$minuteStr';
  }

  /// 根据设备状态获取图标
  String getDeviceMarkerIcon() {
    return 'assets/images/map/car_online.png';
  }

  /// 获取最近3个月的轨迹日历
  Future<void> loadTrackCalendarData() async {
    if (isRefreshTrackCalendar) {
      return;
    }
    trackCalendar.clear();
    var now = DateTime.now();
    ToastUtils.showLoading();
    await getTrackCalendar(now.addMonth(-6), now);
    ToastUtils.dismissLoading();
    isRefreshTrackCalendar = true;
  }

  /// 根据月份获取轨迹日历
  Future<List<DateTime>> getTrackCalendar(DateTime beginDate, DateTime endDate) async {
    var deviceInfo = ref.watch(deviceInfoProvider);
    var calendar = await TrackApi.getTrackCalendar(deviceInfo.imei!, beginDate, endDate);
    trackCalendar.addAll(calendar);
    setState(() {});
    return calendar;
  }
}
